<?php
/**
 * User:ayou chow
 * Date: 2020-02-12
 * Time: 19:33
 */

namespace app\admin\controller;

use app\common\model\AgentModel;
use app\common\model\AgentWithdrawalsModel;
use app\common\model\UserModel;
use app\common\model\UserPromoteModel;
use think\Db;
use think\facade\Request;

class AgentController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function withdrawals()
    {
        return $this->fetch();
    }

    public function withdrawals_edit()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = AgentWithdrawalsModel::get($id);
        $this->assign("withdrawalsinfo", $withdrawalsinfo);
        return $this->fetch();
    }

    public function getlist()
    {
        $id         = Request::param('id');
        $nick_name  = Request::param('nick_name');
        $start_time = Request::param('start_time');
        $end_time   = Request::param('end_time');

        $all = $this->getAllParams();

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];
        if ($id) {
            $where[] = ['uid', '=', $id];
        }
        if (mb_strlen($nick_name, 'UTF-8') > 0) {
            // 查询用户昵称
            $user_ids = UserModel::whereLike('nick_name', "%$nick_name%")->column('id');
            $where[]  = ['uid', 'in', $user_ids];
        }

        if ($start_time) {
            $where[] = ["created_time", ">=", strtotime($start_time)];
        }

        if ($end_time) {
            $where[] = ["created_time", "<=", strtotime($end_time)];
        }

        $order = "id desc";
        if (isset($all["field"]) && $all["field"] && isset($all["order"]) && $all["order"]) {
            $order = sprintf("%s %s", $all["field"], $all["order"]);
        }

        $list = AgentModel::where($where)->with('user')->order($order)->limit(($page - 1) * $limit, $limit)->select()->toArray();
        if (count($list) > 0) {
            $agent_ids = array_column($list, 'uid');

            $agent_count = UserPromoteModel::field('count(id) as count,referer_id')->group('referer_id')->whereIn("referer_id", $agent_ids)->select()->toArray();
            $agent_count = array_column($agent_count, 'count', 'referer_id');

            foreach ($list as &$agent_info) {
                $agent_info['member_count']      = isset($agent_count[$agent_info['uid']]) ? $agent_count[$agent_info['uid']] : 0;
                $agent_info['created_time']      = $agent_info['created_time'] > 0 ? date('Y-m-d H:i:s', $agent_info['created_time']) : '';
                $agent_info['diamond']           = !empty($agent_info['diamond']) ? bcdiv($agent_info['diamond'], 100, 2) : 0;
                $agent_info['withdrawn_diamond'] = !empty($agent_info['withdrawn_diamond']) ? bcdiv($agent_info['withdrawn_diamond'], 100, 2) : 0;
                $agent_info['profit']            = !empty($agent_info['profit']) ? bcdiv($agent_info['profit'], 100, 2) : 0;
                $agent_info['total_profit']      = !empty($agent_info['total_profit']) ? bcdiv($agent_info['total_profit'], 100, 2) : 0;
                //累计获得宝石，diamond 可以领取 withdrawn_diamond 已经领取的
                $agent_info['total_diamond'] = bcadd($agent_info['diamond'], $agent_info['withdrawn_diamond'], 2);
            }

            $count = AgentModel::where($where)->count();
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 邀请人列表
     */
    public function getuser()
    {
        $referer_id = Request::param('referer_id');
        if (Request::isAjax()) {
            $page  = Request::param("page");
            $limit = Request::param("limit");

            $where = [
                ['referer_id', '=', $referer_id]
            ];

            $list = UserPromoteModel::with('user')->where($where)->order('id DESC')->page($page, $limit)->select();

            if (count($list) > 0) {
                $count = UserPromoteModel::where($where)->count();
                foreach ($list as &$item) {
                    $item->created_time = $item->created_time > 0 ? date('Y-m-d H:i:s', $item->created_time) : '';
                }
                return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
            }
            return self::bulidFail("未查询到相关数据");
        }

        $this->assign('referer_id', $referer_id);
        return $this->fetch();
    }

    public function getWithdrawList()
    {
        $id       = Request::param('id');
        $uid      = Request::param('uid');
        $trade_no = Request::param('trade_no');
        $status   = Request::param('status');

        $where = [];
        if ($id) {
            $where['id'] = $id;
        }
        if ($uid) {
            $where['uid'] = $uid;
        }
        if ($trade_no) {
            $where['trade_no'] = $trade_no;
        }
        if ($status != null) {
            $where['status'] = $status;
        }

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $orders = AgentWithdrawalsModel::where($where)->with('agent')->limit(($page - 1) * $limit, $limit)->order("create_time", "desc")->select();
        if (count($orders) > 0) {
            $count = AgentWithdrawalsModel::where($where)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $orders, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function withdrawals_edit_post()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = AgentWithdrawalsModel::get($id);
        if (!$withdrawalsinfo || $withdrawalsinfo->status == 1) {
            return self::bulidFail("提现申请不存在或已处理");
        }
        $trade_no = Request::param('trade_no');
        if ($withdrawalsinfo->save(['trade_no' => $trade_no, 'status' => 1, 'operate_time' => nowFormat()])) {
            return self::bulidSuccess([]);
        }
        return self::bulidFail("处理失败");
    }

    public function withdrawals_edit_refuse()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = AgentWithdrawalsModel::get($id);
        if (!$withdrawalsinfo || $withdrawalsinfo->status == 1) {
            return self::bulidFail("提现申请不存在或已处理");
        }
        Db::startTrans();
        if ($withdrawalsinfo->save(['status' => 2, 'operate_time' => nowFormat()])) {
            //归还余额
            $agent         = AgentModel::where(['uid' => $withdrawalsinfo->uid])->find();
            $agent->profit = ['inc', $withdrawalsinfo->cash];
            if ($agent->save()) {
                Db::commit();
                return self::bulidSuccess([]);
            } else {
                Db::rollback();
                return self::bulidFail("处理失败");
            }
            return self::bulidSuccess([]);
        }
        return self::bulidFail("处理失败");
    }

    public function withdrawals_edit_abnormal()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = AgentWithdrawalsModel::get($id);
        if (!$withdrawalsinfo || $withdrawalsinfo->status == 1) {
            return self::bulidSuccess([]);
        }
        if ($withdrawalsinfo->save(['status' => 3, 'operate_time' => nowFormat()])) {
            return self::bulidSuccess([]);
        }
        return self::bulidFail("处理失败");
    }

    /**
     * 导出好友邀请excel
     * @return \think\response\Download|void
     * @throws \Box\Spout\Common\Exception\IOException
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException
     * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException
     */
    public function excel()
    {
        $id         = Request::param('id');
        $nick_name  = Request::param('nick_name');
        $start_time = Request::param('start_time');
        $end_time   = Request::param('end_time');

        $where = [];
        if ($id) {
            $where[] = ['uid', '=', $id];
        }
        if (mb_strlen($nick_name, 'UTF-8') > 0) {
            // 查询用户昵称
            $user_ids = UserModel::whereLike('nick_name', "%$nick_name%")->column('id');
            $where[]  = ['uid', 'in', $user_ids];
        }

        if ($start_time) {
            $where[] = ["created_time", ">=", strtotime($start_time)];
        }

        if ($end_time) {
            $where[] = ["created_time", "<=", strtotime($end_time)];
        }

        $agent_model = AgentModel::where($where)->with('user');


        $list = [];
        $agent_model->chunk(1000, function ($querys) use (&$list) {
            $agent_ids   = array_column($querys, 'uid');
            $agent_count = UserModel::field('count(id) as count,agentid')->group('agentid')->whereIn("agentid", $agent_ids)->select()->toArray();
            $agent_count = array_column($agent_count, 'count', 'agentid');

            foreach ($querys as $query) {
                $list[] = [
                    $query->id,
                    $query->uid,
                    $query->user ? $query->user->nick_name : '',
                    isset($agent_count[$query->uid]) ? $agent_count[$query->uid] : 0,
                    $query->withdrawn_diamond ?? 0,
                    $query->profit ?? 0,
                    $query->total_profit ?? 0,
                    $query->invite_code,
                    $query->created_time > 0 ? date('Y-m-d H:i:s', $query->created_time) : ''
                ];
            }
        }, 'id', 'desc');

        if (empty($list)) {
            $this->error('没有相关数据');
        }

        $file_title = ['id', '邀请人id', '邀请人昵称', '累计邀请人数', '已领取宝石数', '剩余宝石数', '累计获得宝石数', '邀请码', '创建时间'];
        $file_name  = '好友邀请' . date('Y年m月d日H点');

        // 记录日志
        parent::addAdminLog('导出好友邀请报表');

        return export_excel($list, $file_title, $file_name, '好友邀请');

    }
}